package com.neusoft.elm.util;

import java.sql.*;

/**
 * 事务处理
 *
 */
public class DBUtil {

    private static final ThreadLocal<Connection> TL = new ThreadLocal<Connection>();

    private static final String URL="jdbc:mysql://62.234.13.26:3306/elm?characterEncoding=utf-8";
    private static final String DRIVER="com.mysql.cj.jdbc.Driver";
    private static final String USERNAME="root";
    private static final String PASSWORD="101725";

    //获取Connection（从ThreadLocal中）
    public static Connection getConnection(){
        Connection con = null;
        con = TL.get();
        if(con==null){
            con = createConnection();
            TL.set(con);
        }
        return con;
    }

    //开启事务
    public static void beginTransaction() throws Exception{
        Connection con = null;
        con = TL.get();
        if(con == null){
            con = createConnection();
            //向ThreadLocal中放入一个Connection
            TL.set(con);
        }
        con.setAutoCommit(false);
    }

    //提交事务
    public static void commitTransaction () throws Exception{
        Connection con = TL.get();
        con.commit();
    }

    //回滚一个事务
    public static void rollbackTransaction () throws Exception{
        Connection con = TL.get();
        con.rollback();
    }

    //关闭各种资源
    //TODO 需要理解变量意义
    public static void close(ResultSet rs, PreparedStatement pst){
        try{
            if(rs!=null){
                rs.close();
            }
            if(pst!=null){
                pst.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void close(PreparedStatement pst){
        try{
            if(pst!=null){
                pst.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void close(){
        Connection con = TL.get();
        try{
            if(con!=null){
                con.close();
            }
            //缺失则会导致内存溢出问题
            TL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //创建连接
    private static Connection createConnection() {
        Connection con = null;
        if(con==null){
            try{
                Class.forName(DRIVER);
                con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return con;
    }
}
